package com.itheima.health.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import java.text.ParseException;
import java.util.List;

/**
 * @program: itcast_health
 * @create: 2019-10-17 18:33
 * @author: li he
 * @description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public SysUser loadUserByUsername(String username) {
        return userDao.loadUserByUsername(username);
    }

    //分页查询用户列表数据
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) throws ParseException {
        //开始使用分页助手
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<SysUser> page = userDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page);

    }

    //新增用户
    @Override
    public void add(Integer[] roleIds, SysUser sysUser) {
        userDao.add(sysUser);
        if (roleIds != null && roleIds.length > 0) {

            for (int roleId : roleIds) {
                //在中间表中添加 用户和角色的关联信息
                userDao.addAssociation(sysUser.getId(), roleId);
            }
        }
    }

    //根据id 查询用户数据
    @Override
    public SysUser findById(Integer sysUserId) {
        return userDao.findById(sysUserId);
    }

    //根据用户id 查询 用户关联的角色id
    @Override
    public List<Integer> findRoleIdAssociationUserIds(Integer id) {
        return userDao.findRoleIdAssociationUserIds(id);
    }

    //编辑用户信息
    @Override
    public void edit(Integer[] roleIds, SysUser sysUser) {
        //调用dao修改用户信息
        userDao.edit(sysUser);
        //根据用户id  删除 所关联的角色 id
        userDao.deleteRoleIds(sysUser.getId());
        //根据传过来的角色 id  修改用户所关联的角色id
        if (roleIds!=null&&roleIds.length>0){
            for (Integer roleId : roleIds) {
                userDao.addAssociation(sysUser.getId(),roleId);
            }
        }
    }

    //删除指定id 的用户
    @Override
    public void delById(Integer id) {
        //先删除用户 所关联的角色id
        userDao.deleteRoleIds(id);
        //删除用户
        userDao.delById(id);
    }
}